
package com.hlkj.pay.app.order.impl;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.hlkj.pay.common.constants.MqConstant;
import com.hlkj.pay.config.ExtRocketMQTemplate;
import com.hlkj.pay.dto.payment.MerchantPaymentDetailDto;
import com.hlkj.pay.dto.payment.MerchantPaymentDto;
import com.hlkj.pay.infrastructure.model.payment.MerchantPaymentDetailDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author HlpayTeam
 * @date 2024/10/10 15:30
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MerchantPaymentHandler {

    private final ExtRocketMQTemplate extRocketMQTemplate;

    public void sendStatistics(MerchantPaymentDetailDto merchantPaymentDetailDto) {
        try {
            extRocketMQTemplate.send(MqConstant.PAYMENT_STATISTICS_TOPIC, merchantPaymentDetailDto);
        }
        catch (Exception e) {
            log.error("mq 发送异常:{}", e.getMessage(), e);
        }
    }

    public void sendStatistics(MerchantPaymentDto merchantPaymentDto) {
        try {
            List<MerchantPaymentDetailDO> merchantPaymentDetailList = merchantPaymentDto.getMerchantPaymentDetailList();

            double payOrderAmount = merchantPaymentDetailList.stream().filter(statisticsDto -> statisticsDto.getPayAmount() != null)
                    .mapToDouble(statisticsDto -> statisticsDto.getPayAmount().doubleValue()).sum();

            MerchantPaymentDetailDto merchantPaymentDetailDto = new MerchantPaymentDetailDto();
            merchantPaymentDetailDto.setSn(merchantPaymentDto.getSn());
            merchantPaymentDetailDto.setPaymentType(merchantPaymentDto.getPaymentType());
            merchantPaymentDetailDto.setAppId(merchantPaymentDto.getAppId());
            merchantPaymentDetailDto.setChannelCode(merchantPaymentDto.getChannelCode());
            merchantPaymentDetailDto.setMchChannelCode(merchantPaymentDto.getMchChannelCode());
            if (merchantPaymentDetailDto.getStatus() == null)
                merchantPaymentDetailDto.setStatus(merchantPaymentDto.getStatus());
            merchantPaymentDetailDto.setCreateTime(System.currentTimeMillis());
            if (merchantPaymentDto.getCreateTime() != null)
                merchantPaymentDetailDto.setCreateTime(merchantPaymentDto.getCreateTime());
            merchantPaymentDetailDto.setPayAmount(new BigDecimal(payOrderAmount));
            extRocketMQTemplate.send(MqConstant.PAYMENT_STATISTICS_TOPIC, merchantPaymentDetailDto);
        }
        catch (Exception e) {
            log.error("mq 发送异常:{}", e.getMessage(), e);
        }
    }
}
